package cn.gary.oaserver.config.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: 邓必宏
 * @title:
 * @Demo:
 * @DateTime: 2024/3/18
 */
@Component
public class JwtToken {

    @Value("${jwt.tokenHeader}")
    public String tokenHeader;
    @Value("${jwt.secret}")
    private String secret;//密钥
    @Value("${jwt.expiration}")
    private long expiration;//过期时间
    @Value("${jwt.tokenHead}")
    public String tokenHead;//

    public String createToken(UserDetails user) {
        Date date = new Date ( System.currentTimeMillis ( ) + expiration );
        String token = Jwts.builder ( )
                .setSubject ( user.getUsername () )
                .signWith ( SignatureAlgorithm.HS512, secret )
                .setIssuedAt ( new Date ( ) )
                .setExpiration ( date )
                .compact ( );
        return token;
    }

    public String parseTokenGetUsername(String token)throws Exception {
        Claims claims=null;
        try {
            claims = Jwts.parser ( )
                    .setSigningKey ( secret )
                    .parseClaimsJws ( token )
                    .getBody ( );
            System.out.println ("解析后的用户名为："+claims.getSubject () );
        } catch (Exception e) {
            throw e;
        }
        return claims.getSubject ();
    }
}
